package cn.com.inossem.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import cn.com.inossem.adapter.MessageListAdapter;
import cn.com.inossem.base.RequestActivity;
import cn.com.inossem.model.LiaotianInfoBean;
import cn.com.inossem.utils.ActivityStackControlUtil;
import cn.com.inossem.utils.wangyi.GuessAttachment;
import cn.com.inossem.utils.wangyi.RTSAttachment;
import cn.com.inossem.utils.wangyi.ReminderManager;
import cn.com.inossem.utils.wangyi.SnapChatAttachment;
import cn.com.inossem.utils.wangyi.StickerAttachment;
import cn.com.inossem.utils.wangyi.session.SessionHelper;

import com.foxykeep.datadroid.requestmanager.Request;
import com.netease.nim.uikit.NimUIKit;
import com.netease.nim.uikit.recent.RecentContactsCallback;
import com.netease.nim.uikit.recent.RecentContactsFragment;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.RecentContact;

/**
 * 
 * 消息页
 * 
 * <p>
 * detailed comment
 * 
 * @author szc 2015-8-24
 * @see
 * @since 1.0
 */
public class MessageActivity extends RequestActivity {

	ImageView back;
	ListView listview = null;
	MessageListAdapter adapter = null;
	List<LiaotianInfoBean> retList;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				adapter = new MessageListAdapter(MessageActivity.this, retList);
				listview.setAdapter(adapter);
				break;

			default:
				break;
			}
		}

	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main_tab_layout);
		initView();
		// if (Utils.messageInfo != null)
		// getData(Utils.messageInfo.userInfo.getId() + "");
		addRecentContactsFragment();
	}

	@Override
	public void onDestroy() {
		ActivityStackControlUtil.remove(this);
		super.onDestroy();
	}

	private void initView() {
		retList = new ArrayList<LiaotianInfoBean>();

		back = (ImageView) this.findViewById(R.id.back);
		back.setOnClickListener(this);

		// listview = (ListView) this.findViewById(R.id.listView);

	}

	@Override
	public Request getInitialRequest() {
		return null;

	}

	@Override
	public void onRequestSucess(Request request, Bundle bundle) {

	}

	@Override
	public void onRequestError(int exceptionType) {

	}

	public int getContentViewId() {
		return R.layout.message_layout;

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back:
			setResult(99);
			finish();
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {

			setResult(99);
			finish();

			return true;

		}

		return super.onKeyDown(keyCode, event);

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
		case 1:
			setResult(1);
			finish();
		default:
			break;
		}
	}

	RecentContactsFragment contactsFragment;

	// 将最近联系人列表fragment动态集成进来。开发者也可以使用在xml中配置的方式静态集成。
	private void addRecentContactsFragment() {

		// contactsFragment = new RecentContactsFragment();

		// 设置要集成联系人列表fragment的布局文件
		// contactsFragment.setContainerId(R.id.messages_fragment);

		// ActionBarActivity activity = (TActionBarActivity) getActivity();

		// 如果是activity从堆栈恢复，FM中已经存在恢复而来的fragment，此时会使用恢复来的，而new出来这个会被丢弃掉
		// contactsFragment = (RecentContactsFragment) activity
		// .addFragment(contactsFragment);

		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();

		contactsFragment = new RecentContactsFragment();
		fragmentTransaction.add(R.id.fragment_container, contactsFragment);
		fragmentTransaction.commit();

		// 设置自定义事件回调函数
		contactsFragment.setCallback(new RecentContactsCallback() {
			@Override
			public void onRecentContactsLoaded() {
				// 最近联系人列表加载完毕
				System.out.println("最近联系人列表加载完毕");
			}

			@Override
			public void onUnreadCountChange(int unreadCount) {
				// 未读数发生变化
				ReminderManager.getInstance().updateSessionUnreadNum(
						unreadCount);
			}

			@Override
			public void onItemClick(RecentContact recent) {
				// 回调函数，以供打开会话窗口时传入定制化参数，或者做其他动作
				switch (recent.getSessionType()) {
				case P2P:
					// SessionHelper.startP2PSession(getActivity(),
					// recent.getContactId());
					NimUIKit.startChatting(MessageActivity.this,
							recent.getContactId(), SessionTypeEnum.P2P, SessionHelper.getP2pCustomization());
					break;
				case Team:
					// SessionHelper.startTeamSession(getActivity(),
					// recent.getContactId());
					break;
				default:
					break;
				}
			}

			@Override
			public String getDigestOfAttachment(MsgAttachment attachment) {
				// 设置自定义消息的摘要消息，展示在最近联系人列表的消息缩略栏上
				// 当然，你也可以自定义一些内建消息的缩略语，例如图片，语音，音视频会话等，自定义的缩略语会被优先使用。
				if (attachment instanceof GuessAttachment) {
					GuessAttachment guess = (GuessAttachment) attachment;
					return guess.getValue().getDesc();
				} else if (attachment instanceof RTSAttachment) {
					RTSAttachment rts = (RTSAttachment) attachment;
					return rts.getContent();
				} else if (attachment instanceof StickerAttachment) {
					return "[贴图]";
				} else if (attachment instanceof SnapChatAttachment) {
					return "[阅后即焚]";
				}
				return null;
			}

			@Override
			public String getDigestOfTipMsg(RecentContact recent) {
				String msgId = recent.getRecentMessageId();
				List<String> uuids = new ArrayList<>(1);
				uuids.add(msgId);
				List<IMMessage> msgs = NIMClient.getService(MsgService.class)
						.queryMessageListByUuidBlock(uuids);
				if (msgs != null && !msgs.isEmpty()) {
					IMMessage msg = msgs.get(0);
					Map<String, Object> content = msg.getRemoteExtension();
					if (content != null && !content.isEmpty()) {
						return (String) content.get("content");
					}
				}
				return null;
			}
		});
	}
}